package com.manager.devicemanager.controller;

import com.alibaba.fastjson2.JSONObject;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.config.JwtUtil;
import com.manager.devicemanager.entity.DeviceUser;
import com.manager.devicemanager.entity.UserInfo;
import com.manager.devicemanager.service.IDeviceUserService;
import com.manager.devicemanager.service.IUserInfoService;
import com.manager.devicemanager.util.PWUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wpf
 * @since 2025-05-17
 */
@Tag(name = "登录", description = " 相关接口")
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private IDeviceUserService iDeviceUserService;



    /**
     * 用户登录接口。
     * 本处调用spring security验证功能。（但本项目是前后端分离的，禁用了security登录页功能，
     * 因为其重定向默认只能用“GET”方式请求）
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody UserInfo userInfo) {
        try {


            String loginName = userInfo.getUsername();
            String password = userInfo.getPassword();
            if (loginName == null || loginName.isEmpty() || password == null || password.isEmpty()) {
                return Result.error("用户名或密码不能为空");

            }
            UserInfo userByUsername = iUserInfoService.getUserByUsername(loginName);
            if (userByUsername == null) {
                return Result.error("用户名不存在");
            }
            if (!PWUtils.match(password, userByUsername.getPassword())) {
                return Result.error("密码错误");
            }

//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginName, password);
//        try {
//            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//            SecurityContextHolder.getContext().setAuthentication(authenticate);
            String token = JwtUtil.generateToken(loginName,userByUsername.getId());
            Map<String, Object> map = new HashMap<>();
//            JsonObject jsonObject = new JsonObject();
            map.put("token", token);
            userByUsername.setPassword(null);
            map.put("userInfo", userByUsername);
            List<DeviceUser> deviceUserInfoByUserid = iDeviceUserService.getDeviceUserInfoByUserid(userByUsername.getId());
            JSONObject jsonObject1 = new JSONObject();
            if (deviceUserInfoByUserid != null && deviceUserInfoByUserid.size() > 0) {
                for (DeviceUser deviceUser : deviceUserInfoByUserid) {
                    jsonObject1.put(deviceUser.getDeviceid(), deviceUser.getEditable());
                }
            }
            map.put("roles", new String[]{userByUsername.getRole()});
            map.put("devices", jsonObject1);
            return Result.success(map);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败");
        }
    }




    /**
     * 获取当前用户信息
     * @return 当前用户的详细信息
     */
    @GetMapping("/current")
    public Result<JSONObject> getCurrentUser(HttpServletRequest request) {
       String token = JwtUtil.getTokenFromRequest(request);
        if (token == null || token.isEmpty()) {
            return Result.error("认证信息不存在");
        }
        String userid = JwtUtil.extractUserId(token);
        UserInfo userByUsername = iUserInfoService.getById(userid);
        if (userByUsername == null) {
            return Result.error("用户不存在");
        }
        userByUsername.setPassword(null);
        JSONObject jsonObject = JSONObject.from(userByUsername);
        List<DeviceUser> deviceUserInfoByUserid = iDeviceUserService.getDeviceUserInfoByUserid(userid);
        JSONObject jsonObject1 = new JSONObject();
        if (deviceUserInfoByUserid != null && deviceUserInfoByUserid.size() > 0) {
            for (DeviceUser deviceUser : deviceUserInfoByUserid) {
                jsonObject1.put(deviceUser.getDeviceid(), deviceUser.getEditable());
            }
        }
        jsonObject.put("devices", jsonObject1);
        return Result.success(jsonObject);

    }


}
